<template>
  <div class="article-page">
    <nav class="my-nav van-hairline--bottom">
      <a
        @click="hChange('weight_desc')"
        href="javascript:;"
        >推荐</a
      >
      <a
        @click="hChange(null)"
        href="javascript:;"
        >最新</a
      >
      <div class="logo"><img src="@/assets/logo.png" alt=""></div>
    </nav>
    <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <ArticleItem :item="item" v-for="item in list" :key="item.id"></ArticleItem>
    </van-list>
  </div>
</template>

<script>
import { getArticle } from '@/api/article'
export default {
  name: 'article-page',
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      current: 1,
      sorter: 'weight_desc'
    }
  },
  // async created () {
  //   const res = await getArticle({
  //     current: this.current,
  //     pageSize: 10,
  //     sorter: this.sorter
  //   })
  //   this.list = res.data.rows
  // },
  methods: {
    // 1. load·事件在页面滑动到底部时自动触发
    // 2. 触发时会自动将 loading-改为true，此时我们可以去发请求
    // 3. 请求到数据后，将 -loading·手动改为 false
    // 4. 拿到数据后是将数据追加到当前数组后面
    // 5. 让 current++，准备获取下一页数据
    // 6. 自增完后，判断是否大于总页数(服务器返回的)，如果大于总页数需要将 finished 设置为 true
    async onLoad () {
      const res = await getArticle({
        current: this.current,
        pageSize: 10,
        sorter: this.sorter
      })
      console.log(res)
      this.list.push(...res.data.rows)
      this.loading = false
      this.current++
      if (this.current > res.data.pageTotal) {
        this.finished = true
      }
    },
    async hChange (a) {
      // 1.点击切换获取到
      this.sorter = a
      this.current = 1
      this.list = []
      // 2。重置所有的数据
      this.finished = false
      // 3.发请求
      this.onLoad()
      // 4.loading 状态是 true，因为此刻正在发请求
      this.loading = true
    }
  }
}
</script>

<style lang="less" scoped>
.article-page {
  margin-bottom: 50px;
  margin-top: 44px;
  .my-nav {
    height: 44px;
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    z-index: 999;
    background: #fff;
    display: flex;
    align-items: center;
    > a {
      color: #999;
      font-size: 14px;
      line-height: 44px;
      margin-left: 20px;
      position: relative;
      transition: all 0.3s;
      &::after {
        content: '';
        position: absolute;
        left: 50%;
        transform: translateX(-50%);
        bottom: 0;
        width: 0;
        height: 2px;
        background: #222;
        transition: all 0.3s;
      }
      &.active {
        color: #222;
        &::after {
          width: 14px;
        }
      }
    }
    .logo {
      flex: 1;
      display: flex;
      justify-content: flex-end;
      > img {
        width: 64px;
        height: 28px;
        display: block;
        margin-right: 10px;
      }
    }
  }
}

</style>
